package com.allwees.support.payment.payby.client;

import cn.hutool.core.io.FileUtil;
import com.allwees.bs.core.modelbase.req.SignatureException;
import com.allwees.core.common.context.SpringContextHolder;
import com.allwees.support.payment.payby.configuration.PaybyProperties;
import com.payby.gateway.sdk.PayByClient;
import com.payby.gateway.sdk.cert.KeyCert;
import com.payby.gateway.sdk.config.ApiConfig;
import com.payby.gateway.sdk.config.ClientConfig;
import com.payby.gateway.sdk.config.OkHttpClientConfig;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;

import java.util.ArrayList;
import java.util.List;

public class PayByClients {

    private static PaybyProperties paybyProperties = SpringContextHolder.getBean(PaybyProperties.class);
    private volatile static PayByClient client;

    public static PayByClient getPayByClient()
            throws SignatureException {
        if (null == client) {
            synchronized (PayByClients.class) {
                if (null == client) {
                    ApiConfig apiConfig = new ApiConfig();
                    // setting interface url
                    // Sandbox environment URL
                    apiConfig.setDomain(paybyProperties.getDomain());
                    // Production environment URL
                    // apiConfig.setDomain("https://api.payby.com/sgs/api");

                    // setting pkcs8 privateKey path
                    String merchantPrivateKey = FileUtil.readUtf8String(paybyProperties.getMerchant_private_key_path());
                    // setting publicKey path
                    String payByPubKey = FileUtil.readUtf8String(paybyProperties.getPayby_public_key_path());
                    apiConfig.setCert(new KeyCert(merchantPrivateKey, payByPubKey));
                    // setting http header params
                    apiConfig.setFixHeaders(getFixHeaders(paybyProperties));

                    ClientConfig config =
                            new OkHttpClientConfig.Builder().interceptor(new OkHttpClientConfig.SignInterceptor(apiConfig.getCert()))
                                   .apiConfig(apiConfig).build();
                    client = new PayByClient(config);
                }
            }
        }

        return client;
    }

    public static List<Pair<String, String>> getFixHeaders(PaybyProperties paybyProperties) {
        List<Pair<String, String>> pairs = new ArrayList<>();
        // setting Partner-Id
        pairs.add(new ImmutablePair<>("partner-id", paybyProperties.getPartnerId()));
        // setting group-name Optional
        pairs.add(new ImmutablePair<>("group-name", ""));
        // setting branch-name Optional
        pairs.add(new ImmutablePair<>("branch-name", ""));

        return pairs;
    }

}
